import React from 'react'
import { MoreOutlined } from '@ant-design/icons';
import { Menu, Dropdown, Button } from 'antd';
import qs from 'qs';
export const getSystemIconName = (key) => {
    let fileName = ''
    if (/windows/i.test(key)) {
        fileName = 'Windows.svg'
    } else if(/Ubuntu/i.test(key)) {
        fileName = 'Ubuntu.svg'
    } else if(/CentOS/i.test(key)) {
        fileName = 'CentOS.svg'
    } else if(/openeuler/i.test(key)) {
        fileName = 'openeuler.png'
    }
    return fileName
}

export const getImageIconName = (key) => {
    let fileName = ''
    fileName = key.toLowerCase() + '.png'
    return '/images/' + fileName
}


export const renderTableMoreActions = (btns, item, moreBtnDisabled, 
    opts={clearLinkPadding: true }) => {
    if (btns.length < 1) {
        return null
    }
    const menu = (
        <Menu>
            {
                btns.map((btnDom, btnIndex)=>{
                    return btnDom && <Menu.Item className='more-action-menu' key={btnIndex} style={{textAlign:'center'}}>
                        {btnDom}
                    </Menu.Item>
                })
            }
        </Menu>
    );
    return (
        <Dropdown overlayClassName="table-action-dropdown" overlay={menu} disabled={moreBtnDisabled} placement="bottomCenter">
            <Button className={opts.clearLinkPadding ? 'clear-padding' : ''} type='link'><MoreOutlined /></Button>
        </Dropdown>
    );
}


export const checkResourceIsOperating = (status='') => {
    return status.endsWith('ing') && status != 'Running'
}

/**
 * 根据字典值，获取字典对应的属性值，默认获取label
 * @param {String|Number} value
 * @param {Array} list 字典配置列表，格式如：[{label: '字典1', value: 1},...]
 * @param {String} keys 字典中的属性名称，默认为['label', 'value']
 * @return {String} 匹配结果
 */
export const getMappingAttrByValue = (value, list=[], keys=['label', 'value']) => {
    const [ labelName = 'label', valueName = 'value'] = keys
    const item = list.find(item => item[valueName] === value) || {}
    return item[labelName] || ''
}

// 新开窗口方法，已挂载到window对象中，可以直接调用
export const openWindow = (url, target='_blank') => {
    var user = navigator.userAgent;
    var isiOS = !!user.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); 
    if(isiOS) {
        return window.location.href = url
    }
    const a = document.createElement('a');
    a.href = url;
    a.target = target;
    a.click()
    a.remove && a.remove()
}

export const sortVersionList = (a, b) => {
    // 暂时假设版本号均为x.y.z,且x、y、z均为数字字符串
    const aParts = a.split('.').map(Number);
    const bParts = b.split('.').map(Number);

    for (let i = 0; i < aParts.length; i++) {
        if (aParts[i] > bParts[i]) {
            return -1;
        } else if (aParts[i] < bParts[i]) {
            return 1;
        }
    }

    return 0;
}

// 对弹窗访问文档路径进行处理，文档内部路径改为新窗口打开
// 确保显示和跳转顺利
// id: iframe元素的id
export const iframeDocHandler = (e, reachBottomCb) => {
    setTimeout(_ => {
        const iframe = document.getElementById('docIframe');
        const iframeWindow = iframe.contentWindow;
        const iframeDocument = iframeWindow.document;

        // 预留阅读器滚动到底部事件的监听方法
        // iframeDocument && iframeDocument.addEventListener('scroll', _ => {
        //     const iframeBody = iframeDocument.documentElement || iframeDocument.body;
        //     const scrollTop = iframeBody.scrollTop;
        //     const scrollHeight = iframeBody.scrollHeight;
        //     const clientHeight = iframeBody.clientHeight;
        //     if (scrollTop + clientHeight >= scrollHeight) {
        //         console.log('reach bottom');
        //         reachBottomCb && reachBottomCb()
        //     }
        // })
        const aNodes = iframeDocument.getElementsByTagName('a');
        for (let i = 0; i < aNodes.length; i++) {
            const aNode = aNodes[i];
            let href = aNode.getAttribute('href')
            // 对文档跳转路径进行处理，补充必要的参数
            if (href.startsWith('/') && !href.startsWith('/document')) {
                href = '/document' + href;
                aNode.setAttribute('href', href)
            }
            aNode.setAttribute('target', '_blank')
        }
    }, 400)
}

export function getQueryParam(url, param) {
    const search = url.split('?')[1]
    const searchParams = qs.parse(search);
    return searchParams[param];
}

export function setQueryParam(url, param, value, allowEmpty=false) {
    if(!url) return ''
    const search = url.split('?')[1]
    const searchParams = qs.parse(search);
    if(!allowEmpty && !searchParams[param]) {
        return url
    } 
    searchParams[param] = value;
    const newSearch = qs.stringify(searchParams);
    return url.replace('?' + search, '?' + newSearch);
}

export function isDingTalkAuth() {
    const hash = window.location.hash;
    // 开发和测试环境使用Edg替代DingTalk webview
    const DingTalkAgent = /localhost|172.18.3.200|172.18.3.209/.test(window.location.host) ? 'Edg' : 'DingTalk'
    // console.log(DingTalkAgent, navigator.userAgent, navigator.userAgent.indexOf(DingTalkAgent));
    return navigator.userAgent.indexOf(DingTalkAgent) !== -1
        && /auth/.test(hash)
        && getQueryParam(hash, '_access_code') != undefined;
}

export function isDingTalkAgent() {
    const DingTalkAgent = 'DingTalk'
    return navigator.userAgent.indexOf(DingTalkAgent) !== -1
}

